<template>
  <div class="padding_10">
    <div style="display: flex; margin-left: 10px">
      <div style="margin-right: 10px">
        <span style="color: red; font-size: 20px">*</span>
        <span class="demonstration" style="margin-right: 10px">供货商</span>
        <el-autocomplete
          v-model="supplier"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入供货商"
          @select="handleSelect"
        />
      </div>
      <div>
        <span style="color: red; font-size: 20px">*</span>
        <span class="demonstration" style="margin-right: 10px">备注</span>
        <el-input
          v-model="remarks"
          placeholder="请输入备注"
          style="width: 70%"
        />
      </div>
    </div>
    <div
      v-permissions="{ permission: ['add:InStock'] }"
      style="margin-left: 10px"
    >
      <div style="margin: 10px 0">
        <el-button type="primary" @click="inputSelect">添加</el-button>
        <el-button type="danger" @click.prevent="deleteWarehousing">
          删除
        </el-button>
        <!-- <el-button type="primary" @click="dateClick">选择到期日期</el-button> -->
        <el-button @click="preservation">保存</el-button>
      </div>
    </div>

    <div>
      <table class="tftable" style="width: 100%">
        <thead>
          <tr style="background: #ebeef5">
            <th>勾选删除</th>
            <th>商品名称</th>
            <th>商品条码</th>
            <th>商品价格</th>
            <th>供应商价格</th>
            <th>单位</th>
            <th>总库存</th>
            <th>规格编码</th>
            <th>规格名称</th>
            <th>规格价格</th>
            <th>规格库存</th>
            <th>到期时间</th>
            <th>数量</th>
          </tr>
        </thead>

        <tbody v-for="(item, index) in tableData" :key="index">
          <tr v-if="index > 0">
            <td>
              <span>
                <el-checkbox-group
                  v-model="item.checked"
                  style="height: 50px; margin-top: 30px"
                  @change="checked"
                >
                  <el-checkbox />
                </el-checkbox-group>
              </span>
            </td>
            <td>
              <el-tooltip :content="item.goods_name" placement="top">
                <div
                  style="
                    width: 100px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  "
                >
                  {{ item.goods_name }}
                </div>
              </el-tooltip>
            </td>
            <td>{{ item.goods_code }}</td>
            <td>{{ item.goods_price }}</td>
            <td>
              <el-input
                v-model="item.supply_price"
                placeholder="请输入价格"
                style="width: 130px"
                type="text"
              />
            </td>
            <td>{{ item.unit }}</td>
            <td>{{ item.stock }}</td>
            <td>{{ item.goods_attr_code }}</td>
            <td>{{ item.goods_attr_name }}</td>
            <td>{{ item.goods_attr_price }}</td>
            <td>{{ item.goods_attr_stock }}</td>
            <td>
              <el-input
                v-model="item.expire_at"
                placeholder="请输入到期时间"
                style="width: 130px"
                @focus="inputFoucs(item)"
              />
            </td>
            <td>
              <el-input
                v-model="item.qty"
                placeholder="请输入数量"
                style="width: 130px"
                type="text"
              />
            </td>
          </tr>
        </tbody>
      </table>

      <div
        v-if="tableData.length == 1"
        style="
          width: 98%;
          margin-left: 10px;
          height: 80px;
          text-align: center;
          line-height: 80px;
        "
      >
        暂无数据
      </div>
    </div>

    <!-- 选择到期时间 -->
    <el-dialog
      :before-close="handleClose"
      title="选择到期时间"
      :visible.sync="dialogVisibles"
      width="30%"
    >
      <span>
        <el-date-picker
          v-model="start"
          date-type="time"
          placeholder="生产日期"
          type="date"
          value-format="timestamp"
        />
      </span>
      <span>
        <el-date-picker
          v-model="end"
          date-type="time"
          placeholder="到期日期"
          type="date"
          value-format="timestamp"
        />
      </span>
      <br />
      <div style="margin-top: 10px">
        <span>时间转换(天)</span>
        <span style="margin-left: 10px">
          <el-input
            v-model="transformationItem"
            placeholder="请输入多少天"
            style="width: 130px"
          />
        </span>
        <span style="margin-left: 10px">
          <el-button @click="transformationItemClick">转换</el-button>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibles = false">取 消</el-button>
        <el-button type="primary" @click="SubmitDateClick">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 选择商品 -->
    <el-dialog
      :before-close="handleClose"
      title="商品"
      :visible.sync="dialogVisible"
      width="70%"
    >
      <div>
        <div style="display: flex; margin-bottom: 15px">
          <el-input
            v-model="input"
            placeholder="请输入内容"
            style="width: 50%"
          />
          <el-button @click="search">搜索</el-button>
        </div>
        <el-table
          ref="multipleTable"
          :data="tableData1"
          style="width: 100%"
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            :selectable="selectEnable"
            type="selection"
            width="55"
          />
          <el-table-column
            label="商品名称"
            prop="goods_name"
            show-overflow-tooltip
          />
          <el-table-column label="商品条码" prop="goods_code" />
          <el-table-column label="商品价格" prop="goods_price" />
          <el-table-column label="供应商价格" prop="supply_price" />
          <el-table-column label="	单位" prop="unit" />
          <el-table-column label="总库存" prop="stock" />
          <el-table-column
            label="规格编码"
            prop="goods_attr_code"
            show-overflow-tooltip
          />
          <el-table-column label="规格名称" prop="goods_attr_name" />
          <el-table-column label="规格价格" prop="goods_attr_price" />
          <el-table-column label="规格库存" prop="goods_attr_stock" />
        </el-table>
        <el-pagination
          v-if="total >= 10"
          background
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="Submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  import { goodsInAdd, getGoodsSupplier } from '@/api/commodity'
  import { getGoodsList } from '@/api/public'

  export default {
    components: {},
    data() {
      return {
        form: {},
        input: '',
        remarks: '',
        supplier: '',
        tableData: [
          {
            goods_id: '',
            alias: '',
            type_id: '',
            method_id: '',
            goods_name: '',
            goods_code: '',
            goods_sn: '',
            goods_price: '',
            supply_price: '',
            unit: '',
            stock: '',
            goods_attr_id: '',
            goods_attr_code: '',
            goods_attr_name: '',
            goods_attr_price: '',
            goods_attr_stock: '',
            qty: '',
            batch_sn: '',
            expire_at: '',
            start_at: '',
          },
        ],
        tableData1: [],
        options: [],
        loading: false,
        list: [],
        dialogVisible: false,
        start: '',
        end: '',
        dialogVisibles: false,
        keyIndex: '',
        multipleSelection: [],
        pagesize: 10,
        page: 1,
        supplierId: '',
        dataItem: {},
        transformationItem: '',
        total: '',
      }
    },
    watch: {},
    mounted() {
      this.init()
    },

    methods: {
      init() {
        this.goodsLists()
        getGoodsSupplier().then((e) => {
          this.restaurants = e.data
        })
      },
      goodsLists() {
        const parmas = {
          goods_name: this.input,
          pagesize: this.pagesize,
          page: this.page,
          goods_type: 'entity',
        }
        getGoodsList(parmas).then((res) => {
          this.tableData1 = res.data
        })
      },
      // 添加入库信息
      addWarehousing() {
        this.tableData.push({
          goods_id: '',
          alias: '',
          type_id: '',
          method_id: '',
          goods_name: '',
          goods_code: '',
          goods_sn: '',
          goods_price: '',
          supply_price: '',
          unit: '',
          stock: '',
          goods_attr_id: '',
          goods_attr_code: '',
          goods_attr_name: '',
          goods_attr_price: '',
          goods_attr_stock: '',
          qty: '',
          batch_sn: '',
          expire_at: '',
          start_at: '',
        })
      },
      // 删除商品入库信息
      deleteWarehousing() {
        const arr = []
        this.tableData.forEach((e) => {
          if (!e.checked) {
            arr.push(e)
          }
        })
        this.tableData = arr
      },
      dateClick() {
        this.start = ''
        this.end = ''
        this.transformationItem = ''
        this.dialogVisibles = true
      },
      checked() {},
      // input 选中事件
      inputSelect(index) {
        this.input = ''
        this.goodsLists()
        this.dialogVisible = true
        this.keyIndex = index
      },
      // 转换时间
      transformationItemClick() {
        const item = this.transformationItem * 86400000
        const end = item + this.start
        this.end = end
      },
      search() {
        this.goodsLists()
      },
      // 保存到期时间
      SubmitDateClick() {
        const item = this.end - this.start
        const items = item / 86400000
        if (this.dataItem.goods_attr_code) {
          this.tableData.forEach((e) => {
            if (e.goods_attr_code == this.dataItem.goods_attr_code) {
              this.createdtimeformat(this.end)
              this.createdtimeformats(this.start)
              e.start_at = this.start
              e.expire_at = this.end
              e.effective_at = items
            }
          })
        } else {
          this.tableData.forEach((e) => {
            if (e.checked) {
              this.createdtimeformat(this.end)
              this.createdtimeformats(this.start)
              e.start_at = this.start
              e.expire_at = this.end
              e.effective_at = items
            }
          })
        }

        this.dialogVisibles = false
      },
      createdtimeformat(value) {
        let date = new Date(value)
        let Y = date.getFullYear()
        let M = date.getMonth() + 1
        M = M < 10 ? '0' + M : M
        let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

        this.end = Y + '-' + M + '-' + D
      },
      createdtimeformats(value) {
        let date = new Date(value)
        let Y = date.getFullYear()
        let M = date.getMonth() + 1
        M = M < 10 ? '0' + M : M
        let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

        this.start = Y + '-' + M + '-' + D
      },

      // input 获取焦点事件
      inputFoucs(e) {
        this.start = ''
        this.end = ''
        this.transformationItem = ''
        this.dialogVisibles = true
        this.dataItem = e
      },
      // 弹框的回调
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(() => {
            done()
          })
          .catch(() => {})
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },

      // 多选禁用
      selectEnable(row) {
        if (
          this.tableData.some(
            (item) =>
              item.goods_id === row.goods_id &&
              item.goods_attr_id === row.goods_attr_id
          )
        ) {
          return false
        } else {
          return true // 不禁用
        }
      },

      // 提交
      Submit() {
        this.dialogVisible = false
        this.multipleSelection.forEach((e) => {
          this.tableData.forEach((res) => {
            if (
              e.goods_id != res.goods_id &&
              e.goods_attr_id != res.goods_attr_id
            ) {
              // e.qty = ''
              e.expire_at = ''
              Vue.set(e, 'checked', '')
              this.tableData.splice(this.tableData.length, 0, e)
            }
          })
        })
        for (var i = 0; i < this.tableData.length; i++) {
          for (var j = i + 1; j < this.tableData.length; j++) {
            if (this.tableData[i] == this.tableData[j]) {
              //如果第一个等于第二个，splice方法删除第二个
              this.tableData.splice(j, 1)
              j--
            }
          }
        }
        this.toggleSelection()
      },
      preservation() {
        if (
          this.tableData.length > 1 &&
          this.supplierId != '' &&
          this.remarks != ''
        ) {
          const arr = []
          this.tableData.forEach((e) => {
            if (e.goods_id != '') {
              arr.push({
                goods_id: e.goods_id,
                attribute_id: e.goods_attr_id,
                goods_name: e.goods_name,
                goods_code: e.goods_code,
                goods_sn: e.goods_sn,
                attribute_code: e.goods_attr_code,
                expire_at: e.expire_at,
                qty: e.qty,
                supply_price: e.supply_price,
                unit: e.unit,
                attribute_name: e.goods_attr_name,
                batch_sn: e.batch_sn,
                effective_at: e.effective_at,
                start_at: e.start_at,
              })
            }
          })
          const in_item_data = JSON.stringify(arr)

          const params = {
            in_item_data: in_item_data,
            supplier_id: this.supplierId,
            remark: this.remarks,
          }

          goodsInAdd(params)
            .then((res) => {
              if (res.code == 200) {
                this.tableData = [
                  {
                    goods_id: '',
                    alias: '',
                    type_id: '',
                    method_id: '',
                    goods_name: '',
                    goods_code: '',
                    goods_sn: '',
                    goods_price: '',
                    supply_price: '',
                    unit: '',
                    stock: '',
                    goods_attr_id: '',
                    goods_attr_code: '',
                    goods_attr_name: '',
                    goods_attr_price: '',
                    goods_attr_stock: '',
                    qty: '',
                    expire_at: '',
                    start_at: '',
                  },
                ]
                this.remarks = ''
                this.supplierId = ''
                this.supplier = ''
                this.$message({
                  message: '成功',
                  type: 'success',
                })
              }
            })
            .catch(() => {
              this.$message.error('失败')
            })
        } else {
          if (this.tableData.length < 1) {
            this.$message.error('请填写入库信息')
            return
          }

          if (this.supplierId == '') {
            this.$message.error('请填写供货商信息')
            return
          }
          if (this.remarks == '') {
            this.$message.error('请填写备注信息')
            return
          }
        }
      },
      //queryString 为在框中输入的值
      //callback 回调函数,将处理好的数据推回
      querySearchAsync(queryString, callback) {
        var list = [{}]
        const params = {
          supplier_name: queryString,
        }
        getGoodsSupplier(params).then((e) => {
          e.data.forEach((e) => {
            e.value = e.supplier_name
          })
          list = e.data
          callback(list)
        })
      },
      toggleSelection() {
        this.$refs.multipleTable.clearSelection()
      },
      handleSelect(e) {
        this.supplierId = e.id
      },
    },
  }
</script>
<style>
  /* table.hovertable {
    width: 100%;
    font-family: verdana, arial, sans-serif;
    font-size: 11px;
    color: #333333;
    border-width: 1px;
    border-color: #999999;
    border-collapse: collapse;
  }
  table.hovertable th {
    background-color: #f5f7fa;
    border-width: 1px;
    padding: 8px;
  }
  table.hovertable tr {
    background-color: #fff;
  }
  table.hovertable td {
    text-align: center;
    border-width: 1px;
  } */
  table.tftable,
  table.table-count {
    font-size: 12px;
    color: #333333;
    width: 100%;
    border-width: 1px;
    /* border-collapse: unset; */
    border-spacing: 0;
    border-collapse: unset (collapse/separate);
  }

  table.table-count th,
  table.table-count td {
    font-weight: 400;
    font-style: normal;
    font-size: 12px;
    border-width: 1px;
    border-style: solid;
    border-color: #e4e4e4;
    text-align: center;
  }

  table.tftable th,
  table.tftable td {
    font-weight: 400;
    font-style: normal;
    font-size: 12px;
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #e4e4e4;
    text-align: left;
    text-align: center;
  }

  .tftable {
    /* margin-left: 1%; */
    margin-bottom: 10px;
    margin-top: 10px;
  }
  table.tftable tr:hover {
    background: #c3ecff;
  }
  .tftable > thead > tr:hover {
    background: white;
  }
</style>
